package com.atxiaodei.kabudatourapi.config;

import com.atxiaodei.kabudatourapi.handler.VersionHandlerInterceptor;
import com.atxiaodei.kabudatourapi.handler.jwt.AuthorizationInterceptor;
import com.atxiaodei.kabudatourapi.handler.jwt.TokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//可以使用自定义类扩展MVC的功能
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public VersionHandlerInterceptor getVersionHandlerInterceptor() {
        return new VersionHandlerInterceptor();
    }

    /**
     * token验证和过滤
     * @return
     */
    @Bean
    public AuthorizationInterceptor getAuthCheckInterceptor() {
        return new AuthorizationInterceptor();
    }


    /**
     * token验证和过滤
     * @return
     */
    @Bean
    public TokenInterceptor getTokenInterceptor() {
        return new TokenInterceptor();
    }

    // 拦截器注册
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 1：对所有的请求都进行拦截处理增加版本号处理
        registry.addInterceptor(getVersionHandlerInterceptor()).addPathPatterns("/**");
        // 必须携带auth和openid
        registry.addInterceptor(getAuthCheckInterceptor())
                // 以api开头的都要进行token校验，对登录，支付，文件上传进行过滤拦截
                .addPathPatterns("/api/**");
        // 必须携带token
        registry.addInterceptor(getTokenInterceptor())
                .addPathPatterns("/api/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("*")// 允许跨域访问的源
                .allowedHeaders("*")// 允许头部设置
                .maxAge(168000)// 预检间隔时间
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE");// 允许请求方法
    }

}